package 力扣.栈;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

public class 删除字符串中所有相邻重复项1047 {
    public static void main(String[] args) {
//        String s = "abbaca";
        String s = "s";
        String s1 = removeDuplicates2(s);
        System.out.println(s1);
    }
    public static String removeDuplicates(String S) {
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            int flag = 0;
            while (!stack.isEmpty() && stack.peekFirst() == c){
                stack.pollFirst();
                flag = 1;
            }
            if (flag == 0){
                stack.offerFirst(c);
            }
        }
        StringBuilder ans = new StringBuilder();
        while (!stack.isEmpty()){
            ans.append(stack.pollLast());
        }
        return ans.toString();
    }
    public static String removeDuplicates2(String S) {
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            boolean isC = false;
            while (!stack.isEmpty() && stack.peekLast() == c){
                isC = true;
                stack.pollLast();
            }
            if (!isC){
                stack.add(c);
            }
        }
        StringBuffer stringBuffer = new StringBuffer();
        while (!stack.isEmpty()){
            stringBuffer.append(stack.pollFirst());
        }
        return stringBuffer.toString();
    }
}
